using System.Web.Security;
using Castle.MonoRail.ActiveRecordSupport;
using Castle.MonoRail.Framework;
using Castle.MonoRail.Framework.Filters;
using Rhino.Commons;
using WineCellar.Data;

namespace WineCellar.Web.Controllers
{
    /// <summary>
    /// Application's base class of every controller.
    /// </summary>
    [Resource("layout", "WineCellar.Web.Resources.Layout")]
    [Rescue("generalerror")]
    [LocalizationFilter(RequestStore.Cookie, "locale")]
    public class ApplicationController : ARSmartDispatcherController
    {
        protected const string KEY_MESSAGE = "Message";
        protected const string KEY_ERROR_MESSAGE = "ErrorMessage";
        /// <summary>
        /// Gets a value indicating whether this instance is an ajax request.
        /// </summary>
        public bool IsAjaxRequest
        {
            get
            {
                return Request.Headers["X-Requested-With"] == "XMLHttpRequest";
            }
        }
        /// <summary>
        /// to be used for sending back ajax messages
        /// </summary>
        /// <param name="message"></param>
        protected void SendBackMessage(string message)
        {
            Context.Response.AppendHeader(KEY_MESSAGE, message);
        }

        /// <summary>
        ///to be used to send ajax validation errors back
        /// </summary>
        protected void SendBackErrorMessage(string message)
        {
            Context.Response.Clear();
            Context.Response.StatusCode = 500;
            Context.Response.AppendHeader(KEY_ERROR_MESSAGE, message);
        }

        protected MembershipUser GetLoginMemberShipUser()
        {
            if (Session["memberShipUser"] == null)
            {
                RolePrincipal rolePrincipal = SecurityHelper.GetCurrentUser(Context);
                Session["memberShipUser"] = Membership.GetUser(rolePrincipal.Identity.Name);
            }
            return (MembershipUser)Session["memberShipUser"];
        }
        protected User GetLoginUser()
        {
            if (Session["user"] == null)
            {
                MembershipUser memberUser = GetLoginMemberShipUser();
                Session["user"] = Repository<User>.Load(memberUser.ProviderUserKey);            
            }
            return (User)Session["user"];
        }

        //empty action shared by all controllers
        public void Empty(int id)
        {
            PropertyBag["id"] = id;
            RenderView("shared", "empty");
        }      
    }
}
